package com.jeecg.demo.controller;

import com.jeecg.demo.entity.MtCoreTiaokEntity;
import com.jeecg.demo.entity.MtHetEntity;
import com.jeecg.demo.entity.SysAppMessagesenderEntity;
import com.jeecg.demo.entity.SysAttachmentEntity;
import com.jeecg.demo.entity.VEcpHetinfoEntity;
import com.jeecg.demo.service.MtCoreTiaokServiceI;
import com.jeecg.demo.service.MtHetServiceI;
import com.jeecg.demo.service.MtSlDanjtkServiceI;
import com.jeecg.demo.service.SysAppMessagesenderServiceI;
import com.jeecg.demo.service.SysAttachmentServiceI;
import com.jeecg.demo.service.VEcpHetinfoServiceI;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping({"/vEcpHetStatisinfoController"})
public class VEcpHetStatisinfoController extends BaseController
{
  private static final Logger logger = LoggerFactory.getLogger(VEcpHetStatisinfoController.class);

  @Autowired
  private VEcpHetinfoServiceI vEcpHetinfoService;

  @Autowired
  private MtSlDanjtkServiceI mtSlDanjtkService;

  @Autowired
  private MtCoreTiaokServiceI mtCoreTiaokService;

  @Autowired
  private SystemService systemService;

  @Autowired
  private MtHetServiceI mtHetService;

  @Autowired
  private SysAttachmentServiceI sysAttachmentService;

  @Autowired
  private SysAppMessagesenderServiceI sysAppMessagesender;

  @RequestMapping(params={"list"})
  public ModelAndView list(HttpServletRequest request, String type) { request.setAttribute("type", type);
    return new ModelAndView("com/jeecg/demo/vEcpHetStatisinfoList");
  }

  @RequestMapping(params={"datagrid"})
  public void datagrid(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, String type)
    throws Exception
  {
    CriteriaQuery cq = new CriteriaQuery(VEcpHetinfoEntity.class, dataGrid);

    HqlGenerateUtil.installHql(cq, 
      vEcpHetinfo, request.getParameterMap());
    String ctBegin = request.getParameter("createTime_begin");
    String ctEnd = request.getParameter("createTime_end");
    if ("query".equals(type)) {
      cq.eq("zhuangt", "4");
      cq.eq("dongzbm", "32");
      cq.add();
    }
    if ("queryzq".equals(type)) {
      cq.eq("zhuangt", "4");
      cq.eq("dongzbm", "33");
      cq.add();
    }
    if ((StringUtil.isNotEmpty(ctBegin)) && (StringUtil.isNotEmpty(ctEnd)))
    {
      try {
        if ("confirm".equals(type)) {
          cq.eq("zhuangt", "4");
          cq.add();
        }
        cq.ge("createTime", new SimpleDateFormat("yyyy-MM-dd")
          .parse(ctBegin));
        cq.le("createTime", new SimpleDateFormat("yyyy-MM-dd")
          .parse(ctEnd));
      }
      catch (Exception e) {
        throw new BusinessException(e.getMessage());
      }
      cq.add();
    }
    else {
      cq.add();
    }

    this.vEcpHetinfoService.getDataGridReturn(cq, true);

    String chumdwmc = "";
    String maisdwmc = "";
    if (vEcpHetinfo.getChumdwmc() != null) {
      chumdwmc = vEcpHetinfo.getChumdwmc();
    }
    if (vEcpHetinfo.getMaisdwmc() != null) {
      maisdwmc = vEcpHetinfo.getMaisdwmc();
    }
    String total = "";
    String price = "";
    String totalprice = "";
    if ("query".equals(type)) {
      total = 
        String.valueOf(this.vEcpHetinfoService
        .findOneForJdbc(
        "select round(sum(shul)/10000,2) as ssum from  V_ECP_HETINFO where zhuangt = '4' and DONGZBM = '32' AND CHUMDWMC like '%" +
        chumdwmc + 
        "%' AND MAISDWMC like '%" + 
        maisdwmc + "%'", new Object[0])
        .get("ssum"));
      /*price =
        String.valueOf(this.vEcpHetinfoService
        .findOneForJdbc(
        "select sum(jiag) as price from  V_ECP_HETINFO  where zhuangt = '4' and DONGZBM <> '32' AND CHUMDWMC like '%" + 
        chumdwmc + 
        "%' AND MAISDWMC like '%" + 
        maisdwmc + "%'", new Object[0])
        .get("price"));*/
      totalprice =  String.valueOf(this.vEcpHetinfoService
              .findOneForJdbc(
                      "select round(sum(nvl(jiag,0) * shul)/10000,2) as totalprice from  V_ECP_HETINFO  where zhuangt = '4' and DONGZBM = '32' AND CHUMDWMC like '%" +
                              chumdwmc +
                              "%' AND MAISDWMC like '%" +
                              maisdwmc + "%'", new Object[0])
              .get("totalprice"));
    }
    else {
      total = 
        String.valueOf(this.vEcpHetinfoService
        .findOneForJdbc(
        "select round(sum(shul)/10000,2) as ssum from  V_ECP_HETINFO where zhuangt = '4' and DONGZBM = '33' AND CHUMDWMC like '%" +
        chumdwmc + 
        "%' AND MAISDWMC like '%" + 
        maisdwmc + "%'", new Object[0])
        .get("ssum"));
      /*price =
        String.valueOf(this.vEcpHetinfoService
        .findOneForJdbc(
        "select sum(jiag) as price from  V_ECP_HETINFO  where zhuangt = '4' and DONGZBM = '33' AND CHUMDWMC like '%" + 
        chumdwmc + 
        "%' AND MAISDWMC like '%" + 
        maisdwmc + "%'", new Object[0])
        .get("price"));*/
      totalprice =  String.valueOf(this.vEcpHetinfoService
              .findOneForJdbc(
                      "select round(sum(nvl(jiag,0) * shul)/10000,2) as totalprice from  V_ECP_HETINFO  where zhuangt = '4' and DONGZBM = '33' AND CHUMDWMC like '%" +
                              chumdwmc +
                              "%' AND MAISDWMC like '%" +
                              maisdwmc + "%'", new Object[0])
              .get("totalprice"));
    }

    if ("query".equals(type)) {
      String unit = "万吨";
      String unit1 = "万元";
      /*Double tt = Double.valueOf(total);
      //Double pp = Double.valueOf(price);
      //Double tp = Double.valueOf(tt.doubleValue() * pp.doubleValue());
      Double tp = Double.valueOf(totalprice);
      DecimalFormat df = new DecimalFormat("#.##");

      if (tt.doubleValue() >= 1000.0D) {
        unit = "吨";
        tt = tt;
      }

      if (((tp.doubleValue() >= 10000.0D ? 1 : 0) & (tp.doubleValue() < 100000000.0D ? 1 : 0)) != 0) {
        unit1 = "万元";
        tp = Double.valueOf(tp.doubleValue() / 10000.0D);
      }
      if (tp.doubleValue() >= 100000000.0D) {
        unit1 = "亿";
        tp = Double.valueOf(tp.doubleValue() / 100000000.0D);
      }
      dataGrid.setFooter("shul:" + tt + unit + ",age,daozmch:合计,jiag:" + 
        df.format(tp) + unit1 + ",age,unit:" + "总金额");*/
      dataGrid.setFooter("shul:" + total + unit + ",age,daozmch:合计,jiag:" +
              totalprice + unit1 + ",age,unit:" + "总金额");
    }
    else
    {
      /*String unit = "千克";
      String unit1 = "元";
      Double tt = (double) 0;
      if(total != null && !total.equals("null")){
    	  tt = Double.valueOf(total);
      }
      Double pp = (double) 0;
      if(price != null && !price.equals("null")){
    	  pp = Double.valueOf(price); 
      }
      
      Double tp = Double.valueOf(tt * pp);
      DecimalFormat df = new DecimalFormat("#.##");

      if (tt.doubleValue() >= 1000.0D) {
        unit = "吨";
        tt = tt;
      }

      if (((tp.doubleValue() >= 10000.0D ? 1 : 0) & (tp.doubleValue() < 100000000.0D ? 1 : 0)) != 0) {
        unit1 = "万元";
        tp = Double.valueOf(tp.doubleValue() / 10000.0D);
      }
      if (tp.doubleValue() >= 100000000.0D) {
        unit1 = "亿";
        tp = Double.valueOf(tp.doubleValue() / 100000000.0D);
      }
      dataGrid.setFooter("shul:" + tt + unit + ",age,daozmch:合计,jiag:" + 
        df.format(tp) + unit1 + ",age,unit:" + "总金额");*/
      String unit = "万吨";
      String unit1 = "万元";
      /*Double tt = Double.valueOf(total);
      //Double pp = Double.valueOf(price);
      //Double tp = Double.valueOf(tt.doubleValue() * pp.doubleValue());
      Double tp = Double.valueOf(totalprice);
      DecimalFormat df = new DecimalFormat("#.##");

      if (tt.doubleValue() >= 1000.0D) {
        unit = "吨";
        tt = tt;
      }

      if (((tp.doubleValue() >= 10000.0D ? 1 : 0) & (tp.doubleValue() < 100000000.0D ? 1 : 0)) != 0) {
        unit1 = "万元";
        tp = Double.valueOf(tp.doubleValue() / 10000.0D);
      }
      if (tp.doubleValue() >= 100000000.0D) {
        unit1 = "亿";
        tp = Double.valueOf(tp.doubleValue() / 100000000.0D);
      }
      dataGrid.setFooter("shul:" + tt + unit + ",age,daozmch:合计,jiag:" +
              df.format(tp) + unit1 + ",age,unit:" + "总金额");*/
      dataGrid.setFooter("shul:" + total + unit + ",age,daozmch:合计,jiag:" +
              totalprice + unit1 + ",age,unit:" + "总金额");
    }

    TagUtil.datagrid(response, dataGrid);
  }

  @RequestMapping(params={"doDel"})
  @ResponseBody
  public AjaxJson doDel(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest request)
  {
    String message = null;
    AjaxJson j = new AjaxJson();
    vEcpHetinfo = (VEcpHetinfoEntity)this.systemService.getEntity(VEcpHetinfoEntity.class, 
      vEcpHetinfo.getId());
    message = "删除成功";
    try {
      this.vEcpHetinfoService.delete(vEcpHetinfo);
      this.systemService.addLog(message, Globals.Log_Type_DEL, 
        Globals.Log_Leavel_INFO);
    }
    catch (Exception e) {
      e.printStackTrace();
      message = "删除失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  @RequestMapping(params={"doBatchDel"})
  @ResponseBody
  public AjaxJson doBatchDel(String ids, HttpServletRequest request)
  {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "删除成功";
    try {
      for (String id : ids.split(",")) {
        VEcpHetinfoEntity vEcpHetinfo = (VEcpHetinfoEntity)this.systemService.getEntity(
          VEcpHetinfoEntity.class, Integer.valueOf(Integer.parseInt(id)));
        this.vEcpHetinfoService.delete(vEcpHetinfo);
        this.systemService.addLog(message, Globals.Log_Type_DEL, 
          Globals.Log_Leavel_INFO);
      }
    }
    catch (Exception e) {
      e.printStackTrace();
      message = "删除失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  @RequestMapping(params={"doAdd"})
  @ResponseBody
  public AjaxJson doAdd(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest request)
  {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "添加成功";
    try {
      this.vEcpHetinfoService.save(vEcpHetinfo);
      this.systemService.addLog(message, Globals.Log_Type_INSERT, 
        Globals.Log_Leavel_INFO);
    }
    catch (Exception e) {
      e.printStackTrace();
      message = "添加失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  @RequestMapping(params={"doUpdate"})
  @ResponseBody
  public AjaxJson doUpdate(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest request)
  {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "更新成功";
    VEcpHetinfoEntity t = (VEcpHetinfoEntity)this.vEcpHetinfoService.get(VEcpHetinfoEntity.class, 
      vEcpHetinfo.getId());
    try {
      MyBeanUtils.copyBeanNotNull2Bean(vEcpHetinfo, t);
      this.vEcpHetinfoService.saveOrUpdate(t);
      this.systemService.addLog(message, Globals.Log_Type_UPDATE, 
        Globals.Log_Leavel_INFO);
    }
    catch (Exception e) {
      e.printStackTrace();
      message = "更新失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  @RequestMapping(params={"goAdd"})
  public ModelAndView goAdd(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest req)
  {
    if (StringUtil.isNotEmpty(vEcpHetinfo.getId())) {
      vEcpHetinfo = (VEcpHetinfoEntity)this.vEcpHetinfoService.getEntity(VEcpHetinfoEntity.class, 
        vEcpHetinfo.getId());
      req.setAttribute("vEcpHetinfoPage", vEcpHetinfo);
    }
    return new ModelAndView("com/jeecg/demo/vEcpHetinfo-add");
  }

  @RequestMapping(params={"goUpdate"})
  public ModelAndView goUpdate(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest req)
  {
    if (StringUtil.isNotEmpty(vEcpHetinfo.getId())) {
      vEcpHetinfo = (VEcpHetinfoEntity)this.vEcpHetinfoService.getEntity(VEcpHetinfoEntity.class, 
        vEcpHetinfo.getId());
      req.setAttribute("vEcpHetinfoPage", vEcpHetinfo);
    }
    return new ModelAndView("com/jeecg/demo/vEcpHetinfo-update");
  }

  @RequestMapping(params={"upload"})
  public ModelAndView upload(HttpServletRequest req)
  {
    req.setAttribute("controller_name", "vEcpHetinfoController");
    return new ModelAndView("common/upload/pub_excel_upload");
  }

  @RequestMapping(params={"exportXls"})
  public String exportXls(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap)
  {
    CriteriaQuery cq = new CriteriaQuery(VEcpHetinfoEntity.class, dataGrid);
    HqlGenerateUtil.installHql(cq, 
      vEcpHetinfo, request.getParameterMap());
    List vEcpHetinfos = this.vEcpHetinfoService
      .getListByCriteriaQuery(cq, Boolean.valueOf(false));
    modelMap.put("fileName", "V_ECP_HETINFO");
    modelMap.put("entity", VEcpHetinfoEntity.class);
    modelMap.put("params", 
      new ExportParams("V_ECP_HETINFO列表", "导出人:" + 
      ResourceUtil.getSessionUser().getRealName(), "导出信息"));
    modelMap.put("data", vEcpHetinfos);
    return "jeecgExcelView";
  }

  @RequestMapping(params={"exportXlsByT"})
  public String exportXlsByT(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap)
  {
    modelMap.put("fileName", "V_ECP_HETINFO");
    modelMap.put("entity", VEcpHetinfoEntity.class);
    modelMap.put("params", 
      new ExportParams("V_ECP_HETINFO列表", "导出人:" + 
      ResourceUtil.getSessionUser().getRealName(), "导出信息"));
    modelMap.put("data", new ArrayList());
    return "jeecgExcelView";
  }

 

  @RequestMapping(params={"goConfirm"})
  public ModelAndView confirmPact(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest req, int flag)
  {
    if (StringUtil.isNotEmpty(vEcpHetinfo.getId())) {
      vEcpHetinfo = (VEcpHetinfoEntity)this.vEcpHetinfoService.getEntity(VEcpHetinfoEntity.class, 
        vEcpHetinfo.getId());
      req.setAttribute("vEcpHetinfoPage", vEcpHetinfo);
      req.setAttribute("confirmflag", Integer.valueOf(flag));
    }

    CriteriaQuery cq = new CriteriaQuery(MtCoreTiaokEntity.class);
    cq.add();

    List resultList = this.mtCoreTiaokService
      .getListByCriteriaQuery(cq, Boolean.valueOf(false));
    req.setAttribute("tiaoKList", resultList);

    CriteriaQuery cq1 = new CriteriaQuery(SysAttachmentEntity.class);
    cq1.eq("objid", Integer.valueOf(vEcpHetinfo.getHetid()));
    cq1.addOrder("sysid", SortDirection.asc);
    cq1.add();

    String sql = "SELECT * from SYS_ATTACHMENT t WHERE t.OBJURL is not null and t.OBJID=? ORDER BY t.SYSID desc";
    List sysAttachList = this.systemService.findForJdbc(
      sql, new Object[] { vEcpHetinfo.getSysid() });
    if (sysAttachList.size() > 3)
      sysAttachList = sysAttachList.subList(0, 3);
    req.setAttribute("sysAttachList", sysAttachList);
    req.setAttribute("prefixUrl", 
      ResourceUtil.getConfigByName("imageServerUrl"));
    return new ModelAndView("com/jeecg/demo/hetquery");
  }

  @RequestMapping(params={"doConfirm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public AjaxJson doConfirm(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest request)
  {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "更新失败";

    CriteriaQuery cq = new CriteriaQuery(MtHetEntity.class);
    cq.eq("hetid", vEcpHetinfo.getHetid());
    cq.add();

    List mtList = this.mtHetService.getListByCriteriaQuery(cq, 
      Boolean.valueOf(false));
    MtHetEntity mt = null;
    vEcpHetinfo = 
      (VEcpHetinfoEntity)this.vEcpHetinfoService
      .findByQueryString(
      "from VEcpHetinfoEntity v where v.hetid = '" + 
      vEcpHetinfo.getHetid() + "'").get(0);
    if (mtList.size() > 0) {
      mt = (MtHetEntity)mtList.get(0);
      try {
        mt.setZhuangt("4");
        this.mtHetService.save(mt);
        this.systemService.addLog(message, Globals.Log_Type_UPDATE, 
          Globals.Log_Leavel_INFO);
        message = "更新成功";
        String url = "http://10.2.2.114:8080/jeecg-boot/api/contront/saveHetinfo";
        RestTemplate template = new RestTemplate();
        LinkedMultiValueMap params = new LinkedMultiValueMap();
        JSONObject jsmt = JSONObject.fromObject(vEcpHetinfo);
        System.out.print(jsmt.toString());
        params.add("json", jsmt.toString());
        HttpHeaders headers = new HttpHeaders();
        MediaType type = 
          MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity req = new HttpEntity(
          params, headers);
        String ret = "";
        ret = (String)template.postForObject(url, req, String.class, new Object[0]);

        SysAppMessagesenderEntity appmessage = new SysAppMessagesenderEntity();
        appmessage.setSender(Integer.valueOf(0));
        appmessage.setReceiver(Integer.valueOf(vEcpHetinfo.getHetid()));
        appmessage.setOrderid(Integer.valueOf(1));
        appmessage.setMsgstatus("1");
        appmessage.setIsvalid("1");
        appmessage.setAppid("1");
        appmessage.setSendtime(new Date());
        appmessage.setFixedtime(new Date());

        String msg = "您的合同" + vEcpHetinfo.getHetbh() + 
          "已通过,您可到合同列表中查看。";
        appmessage.setMsgtitle(msg);
        appmessage.setMsgcontent(msg);
        this.sysAppMessagesender.save(appmessage);
      }
      catch (Exception e)
      {
        e.printStackTrace();
        message = "更新失败";
        throw new BusinessException(e.getMessage());
      }
    }

    j.setMsg(message);
    return j;
  }

  @RequestMapping(params={"doBack"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public AjaxJson doBack(VEcpHetinfoEntity vEcpHetinfo, HttpServletRequest request)
  {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "退回失败";

    CriteriaQuery cq = new CriteriaQuery(MtHetEntity.class);
    cq.eq("hetid", vEcpHetinfo.getHetid());
    cq.add();

    List mtList = this.mtHetService.getListByCriteriaQuery(cq, 
      Boolean.valueOf(false));
    MtHetEntity mt = null;

    if (mtList.size() > 0) {
      mt = (MtHetEntity)mtList.get(0);
      try
      {
        mt.setZhuangt("1");
        this.mtHetService.save(mt);
        this.systemService.addLog(message, Globals.Log_Type_UPDATE, 
          Globals.Log_Leavel_INFO);
        message = "退回成功";

        SysAppMessagesenderEntity appmessage = new SysAppMessagesenderEntity();
        appmessage.setSender(Integer.valueOf(0));
        appmessage.setReceiver(Integer.valueOf(vEcpHetinfo.getHetid()));
        appmessage.setOrderid(Integer.valueOf(1));
        appmessage.setMsgstatus("1");
        appmessage.setIsvalid("1");
        appmessage.setAppid("1");
        appmessage.setSendtime(new Date());
        appmessage.setFixedtime(new Date());

        String msg = "您的合同" + vEcpHetinfo.getHetbh() + 
          "已退回,您可到合同列表中查看。";
        appmessage.setMsgtitle(msg);
        appmessage.setMsgcontent(msg);
      }
      catch (Exception e) {
        e.printStackTrace();
        message = "退回失败";
        throw new BusinessException(e.getMessage());
      }
    }

    j.setMsg(message);
    return j;
  }
}